package cn.kgc.shiroday03.service.impl;

import cn.kgc.shiroday03.commons.CodeMsg;
import cn.kgc.shiroday03.commons.ResponseResult;
import cn.kgc.shiroday03.entity.Permission;
import cn.kgc.shiroday03.entity.RolePers;
import cn.kgc.shiroday03.mapper.PermissionMapper;
import cn.kgc.shiroday03.mapper.RolePersMapper;
import cn.kgc.shiroday03.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService{

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePersMapper rolePersMapper;

    @Override
    public ResponseResult treeSelect() {

        List<Permission> permissions = permissionMapper.selectList(null);
        List<Permission> collect = permissions.stream().filter(permission -> permission.getIsMenu() != 2).collect(Collectors.toList());


        return new ResponseResult(CodeMsg.SUCCESS,null,collect);
    }

    @Override
    public ResponseResult deleteById(Integer id) {

        //  1.判定删除的权限是否含有子菜单
        LambdaQueryWrapper<Permission> lambda = new QueryWrapper<Permission>().lambda();
        lambda.eq(Permission::getParentId,id);
        List<Permission> permissions = permissionMapper.selectList(lambda);
        if (permissions.size()>0){
            return  new ResponseResult(CodeMsg.HAS_SUBMENU);
        }

        // 2.根据id删除权限
        permissionMapper.deleteById(id);
        // 3. 角色权限管理表中的数据 role_permission
        LambdaQueryWrapper<RolePers> lambda1 = new QueryWrapper<RolePers>().lambda();
        lambda1.eq(RolePers::getPerId,id);
        rolePersMapper.delete(lambda1);

        return new ResponseResult(CodeMsg.SUCCESS);
    }
}




